<template>
  <view class="page">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-bar-left">
        <view class="nav-icon" @click="handleBack">
          <uni-icons type="left" size="20" color="#333"/>
        </view>
        <view class="nav-icon" @click="goToHome">
          <uni-icons type="home" size="20" color="#333"/>
        </view>
      </view>
      <view class="nav-bar-title">
        选择时间
      </view>
    </view>

    <!-- 医生信息卡片 -->
    <view class="doctor-card">
      <image class="avatar" :src="doctorInfo.photo" mode="aspectFill" />
      <view class="info">
        <view class="name-title">
          <text class="name">{{ doctorInfo.name }}</text>
          <text class="title">{{ doctorInfo.job }}</text>
        </view>
        <view class="remark" v-if="doctorInfo.remark">{{ doctorInfo.remark }}</view>
        <view class="price">挂号费：¥{{ doctorInfo.price }}</view>
        <view class="desc">{{ doctorInfo.description }}</view>
      </view>
    </view>

    <!-- 选择问诊方式 -->
    <view class="section">
      <view class="section-title">选择问诊方式</view>
      <view class="visit-types">
        <view 
          v-for="(type, index) in visitTypes" 
          :key="index"
          :class="['visit-type', selectedType === index ? 'active' : '']"
          @click="selectType(index)"
        >
          <uni-icons :type="type.icon" size="24" color="#333"/>
          <text>{{ type.name }}</text>
        </view>
      </view>
    </view>

    <!-- 选择时间段 -->
    <view class="section">
      <view class="section-title">选择时间段</view>
      <view class="time-slots">
        <view 
          v-for="(slot, index) in timeSlots" 
          :key="index"
          :class="['time-slot', 
            selectedSlot === index ? 'active' : '',
            !availableSlots.includes(index + 1) ? 'disabled' : '',
            scheduleData.some(item => item.slot === index + 1) && isTimeSlotFull(index) ? 'full' : ''
          ]"
          @click="selectSlot(index)"
        >
          {{ slot }}
          <text :class="{
            'available': availableSlots.includes(index + 1),
            'unavailable': !availableSlots.includes(index + 1),
            'full': scheduleData.some(item => item.slot === index + 1) && isTimeSlotFull(index)
          }">{{ getTimeSlotStatusText(index) }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button">
      <button class="submit-btn" @click="handleSubmit">确认预约</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { apiBaseUrl } from '../../../config/api'
declare const uni: any;
declare const getCurrentPages: () => any[];

// 时间段列表
const timeSlots = [
  '08:00~08:30', '08:30~09:00', '09:00~09:30', '09:30~10:00',
  '10:00~10:30', '10:30~11:00', '11:00~11:30', '11:30~12:00',
  '13:00~13:30', '13:30~14:00', '14:00~14:30', '14:30~15:00',
  '15:00~15:30', '15:30~16:00', '16:00~16:30'
];

// 问诊方式
const visitTypes = [
  { name: '视频问诊', icon: 'videocam' },
  { name: '图文问诊', icon: 'chat' },
  { name: '门诊就医', icon: 'location' }
]

// 页面状态
const doctorInfo = ref({
  name: '',
  photo: '',
  job: '',
  deptName: '',
  description: '',
  price: 0,
  remark: ''
})
const selectedType = ref(-1)
const selectedSlot = ref(-1)
const doctorId = ref('')
const appointmentDate = ref('')
const deptSubId = ref('')

// 可用的时间段（将从后端获取）
const availableSlots = ref<number[]>([])
const scheduleData = ref<any[]>([])

// 获取医生详情
const getDoctorInfo = async () => {
  try {
    const res = await uni.request({
      url: apiBaseUrl + '/doctors/selectDoctorInfoById',
      method: 'POST',
      data: {
        id: doctorId.value
      }
    })

    if (res.statusCode === 200 && res.data.code === 200) {
      doctorInfo.value = res.data.result
    }
  } catch (error) {
    uni.showToast({
      title: '获取医生信息失败',
      icon: 'none'
    })
  }
}

// 选择问诊方式
const selectType = (index: number) => {
  selectedType.value = index
}

// 选择时间段
const selectSlot = (index: number) => {
  // 检查是否是可用时间段
  if (!availableSlots.value.includes(index + 1)) {
    // 判断是否是已满的时间段
    if (isTimeSlotFull(index) && scheduleData.value.some(item => item.slot === index + 1)) {
      uni.showToast({
        title: '该时间段已约满',
        icon: 'none'
      })
    } 
    // 判断是否是过期的时间段
    else if (isTimeSlotPassed(index)) {
      uni.showToast({
        title: '该时间段已过期',
        icon: 'none'
      })
    }
    // 其他情况 - 无医生出诊
    else if (!scheduleData.value.some(item => item.slot === index + 1)) {
      uni.showToast({
        title: '无医生出诊，请选择其他时段',
        icon: 'none'
      })
    }
    // 其他不可预约情况
    else {
      uni.showToast({
        title: '该时间段不可预约',
        icon: 'none'
      })
    }
    return
  }
  
  selectedSlot.value = index
}

// 判断时间段是否已过期
const isTimeSlotPassed = (index: number): boolean => {
  // 如果不是今天的预约，不需要判断时间
  const today = new Date().toISOString().split('T')[0]
  if (appointmentDate.value !== today) {
    return false
  }
  
  // 获取当前时间
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()
  
  // 解析时间段
  const timeSlot = timeSlots[index]
  const endTime = timeSlot.split('~')[1]
  const [endHour, endMinute] = endTime.split(':').map(Number)
  
  // 判断当前时间是否已经超过时间段结束时间
  return (currentHour > endHour) || (currentHour === endHour && currentMinute >= endMinute)
}

// 获取医生工作计划
const getDoctorWorkPlan = async () => {
  try {
    const res = await uni.request({
      url: apiBaseUrl + '/doctor/work/plan/schedule/selectDoctorWorkPlanSchedule',
      method: 'POST',
      data: {
        doctorId: doctorId.value,
        date: appointmentDate.value,
        deptSubId: deptSubId.value
      }
    })

    if (res.statusCode === 200 && res.data.code === 200) {
      scheduleData.value = res.data.result
      // 提取可用的时间段号码 - 只提取未满的时间段
      availableSlots.value = res.data.result
        .filter(item => item.maximum > item.num) // 只保留还有余量的时间段
        .map(item => item.slot)
      console.log('可用时间段:', availableSlots.value)
      console.log('所有排班数据:', scheduleData.value)
    }
  } catch (error) {
    console.error('获取医生工作计划失败:', error)
    uni.showToast({
      title: '获取可用时间段失败',
      icon: 'none'
    })
  }
}

// 判断时间段是否已满
const isTimeSlotFull = (index: number): boolean => {
  // 检查对应的排班记录
  const slotData = scheduleData.value.find(item => item.slot === index + 1)
  // 如果找到排班记录且已满
  return slotData ? slotData.maximum <= slotData.num : true
}

// 获取时间段状态文本
const getTimeSlotStatusText = (index: number): string => {
  // 首先检查是否在可用时间段列表中
  if (!scheduleData.value.some(item => item.slot === index + 1)) {
    return '不可约'
  }
  
  // 检查是否已过期
  if (isTimeSlotPassed(index)) {
    return '已过期'
  }
  
  // 检查是否已满
  if (isTimeSlotFull(index)) {
    return '已约满'
  }
  
  // 都通过，则可预约
  return '可预约'
}

// 提交预约
const handleSubmit = () => {
  // 先检查是否已登录
  if (!patientId || !patientName) {
    uni.showToast({
      title: '请先登录后再预约',
      icon: 'none',
      duration: 2000
    })
    
    // 延迟跳转到用户页面
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/user/user'
      })
    }, 1500)
    return
  }
  
  if (selectedType.value === -1) {
    uni.showToast({
      title: '请选择问诊方式',
      icon: 'none'
    })
    return
  }
  if (selectedSlot.value === -1) {
    uni.showToast({
      title: '请选择时间段',
      icon: 'none'
    })
    return
  }
  
  // 再次检查时间是否已过期
  if (isTimeSlotPassed(selectedSlot.value)) {
    uni.showToast({
      title: '该时间段已过期',
      icon: 'none'
    })
    return
  }
  
  // 再次检查时间段是否已满
  if (isTimeSlotFull(selectedSlot.value)) {
    uni.showToast({
      title: '该时间段已约满',
      icon: 'none'
    })
    return
  }
  
  // 查找所选时间段对应的排班信息
  const selectedSchedule = scheduleData.value.find(item => item.slot === selectedSlot.value + 1)
  if (!selectedSchedule || !selectedSchedule.scheduleId) {
    uni.showToast({
      title: '预约信息错误',
      icon: 'none'
    })
    return
  }
  
  // 创建订单
  createOrder(selectedSchedule)
}

// 创建订单
const createOrder = async (schedule) => {
  try {
    // 再次检查用户登录状态
    if (!patientId || !patientName) {
      uni.showToast({
        title: '请先登录后再预约',
        icon: 'none',
        duration: 2000
      })
      
      // 延迟跳转到用户页面
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/user/user'
        })
      }, 1500)
      return
    }
    
    uni.showLoading({
      title: '创建订单中'
    })

    console.log('创建订单参数:', {
      workPlanId: schedule.workPlanId,
      scheduleId: schedule.scheduleId,
      appointmentDate: appointmentDate.value,
      doctorId: doctorId.value,
      deptSubId: deptSubId.value,
      deptName: doctorInfo.value.deptName,
      amount: doctorInfo.value.price,
      timeSlot: selectedSlot.value + 1,
      doctorName: doctorInfo.value.name,
      visitType: visitTypes[selectedType.value].name,
      patientId: patientId,
      patientName: patientName
    })
    
    const res = await uni.request({
      url: apiBaseUrl + '/patient/appointment/order/create',
      method: 'POST',
      data: {
        workPlanId: schedule.workPlanId,
        scheduleId: schedule.scheduleId,
        appointmentDate: appointmentDate.value,
        doctorId: doctorId.value,
        deptSubId: deptSubId.value,
        deptName: doctorInfo.value.deptName,
        amount: doctorInfo.value.price,
        timeSlot: selectedSlot.value + 1,
        doctorName: doctorInfo.value.name,
        visitType: visitTypes[selectedType.value].name,
        patientId: patientId,
        patientName: patientName
      }
    })
    
    uni.hideLoading()
    
    if (res.statusCode === 200 && res.data.code === 200) {
      // 创建订单成功，跳转到预约成功页面
      uni.navigateTo({
        url: `/pages/index/Make-appointment/appointment-success?orderId=${res.data.result.orderId}`
      })
    } else {
      uni.showToast({
        title: res.data.message || '创建订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '创建订单失败',
      icon: 'none'
    })
    console.error('创建订单失败:', error)
  }
}

const patientInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
const patientName = patientInfo.nickname
const patientId = uni.getStorageSync('id')

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 返回主页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options
  
  if (options?.doctorId) {  // 只要求doctorId必须存在
    doctorId.value = options.doctorId
    // 如果没有传date参数，使用当前日期
    appointmentDate.value = options?.date || new Date().toISOString().split('T')[0]
    if (options?.deptSubId) {
      deptSubId.value = options.deptSubId
    }
    getDoctorInfo()
    getDoctorWorkPlan() // 获取医生的工作计划
  } else {
    uni.showToast({
      title: '缺少必要参数',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})
</script>

<style>
.page {
  min-height: 100vh;
  background: #f5f8ff;
  padding-bottom: env(safe-area-inset-bottom);
  padding-top: calc(var(--status-bar-height) + 44px + 20rpx);
}

.nav-bar {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 44px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
}

.nav-bar-left {
  display: flex;
  align-items: center;
}

.nav-icon {
  width: 44rpx;
  height: 44px;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.nav-bar-title {
  flex: 1;
  text-align: center;
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.doctor-card {
  margin: 20rpx;
  margin-top: 20rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  display: flex;
}

.doctor-card .avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 20rpx;
}

.doctor-card .info {
  flex: 1;
}

.doctor-card .name-title {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.doctor-card .name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-right: 12rpx;
}

.doctor-card .title {
  font-size: 24rpx;
  color: #666;
  background: #f5f8ff;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.doctor-card .remark {
  font-size: 24rpx;
  color: #2979ff;
  margin-bottom: 8rpx;
  background: #e8f3ff;
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.doctor-card .price {
  font-size: 26rpx;
  color: #f56c6c;
  margin-bottom: 8rpx;
}

.doctor-card .desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.section {
  margin: 20rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.visit-types {
  display: flex;
  justify-content: space-around;
}

.visit-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 40rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
}

.visit-type text {
  font-size: 28rpx;
  color: #333;
  margin-top: 12rpx;
}

.visit-type.active {
  background: #e8f3ff;
  border-color: #2979ff;
  color: #2979ff;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.time-slot {
  width: calc(33.33% - 20rpx);
  height: 120rpx;
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  position: relative;
  transition: all 0.3s ease;
}

.time-slot.active {
  border: 2rpx solid #2979ff;
  background: rgba(41, 121, 255, 0.05);
}

.time-slot.disabled {
  opacity: 0.6;
  background: #f8f8f8;
}

.time-slot.full {
  opacity: 0.6;
  background: #fff0f0;
}

.time-slot text {
  font-size: 24rpx;
  margin-top: 8rpx;
}

.time-slot text.available {
  color: #07c160;
}

.time-slot text.unavailable {
  color: #999;
}

.time-slot text.full {
  color: #f56c6c;
}

.bottom-button {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #2979ff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}
</style> 